import cmd
from serial_disk_interface import SerialDiskInterface

class SerialDiskCLI(SerialDiskInterface, cmd.Cmd):
    intro = 'Welcome to Serial Disk CLI. Type help or ? to list commands.\n'
    prompt = '(serial_disk) '
    
    def __init__(self, config_path):
        SerialDiskInterface.__init__(self, config_path)
        cmd.Cmd.__init__(self)
        
    def start(self):
        """启动CLI应用"""
        self.cmdloop()
        
    def stop(self):
        """停止CLI应用"""
        if self.device_manager:
            self.device_manager.disconnect()
        self.config_manager.save()
        
    def handle_transfer_progress(self, progress, status):
        """处理传输进度"""
        print(f"\rProgress: {progress:.1f}% - {status}", end='')
        
    def handle_transfer_complete(self, success, error):
        """处理传输完成"""
        print()  # 换行
        if success:
            print("Transfer complete")
        else:
            print(f"Transfer failed: {error}")
            
    def handle_device_error(self, error):
        """处理设备错误"""
        print(f"Device error: {error}")
        
    def do_connect(self, arg):
        """连接设备: connect <port>"""
        if not arg:
            print("Error: Port required")
            return
            
        if self.device_manager.connect(arg):
            print(f"Connected to {arg}")
        else:
            print("Connection failed")
            
    def do_disconnect(self, arg):
        """断开连接"""
        self.device_manager.disconnect()
        print("Disconnected")
        
    def do_ls(self, arg):
        """列出文件: ls [path]"""
        path = arg or self.config_manager.get('device_path')
        files = self.device_manager.list_device_files(path)
        if files:
            for file in files:
                print(f"{file['name']:30} {file['size']:10} {file['type']}")
                
    def do_quit(self, arg):
        """退出程序"""
        return True 